from django.shortcuts import render, redirect, HttpResponse
from django.contrib import auth
from django.contrib.auth.decorators import login_required, REDIRECT_FIELD_NAME
from api.utils.common import MyResponse
from django.http import JsonResponse
from io import BytesIO
from api.utils import common
from api import models
from django.db.models import Q,F
from django.db import transaction
import datetime
import xlwt
import os

@login_required(redirect_field_name=REDIRECT_FIELD_NAME, login_url='/login/')
def index(request):
    username = request.user
    user = models.UserInfo.objects.filter(name=username).first()
    if user.user_type == 0:
        url = 'backend/stu.html'
    elif user.user_type == 1:
        url = 'backend/reg.html'
    elif user.user_type == 2:
        url = 'backend/exa.html'
    else:
        url = 'error.html'
    return render(request, url, locals())


# 参与的活动
@login_required(redirect_field_name=REDIRECT_FIELD_NAME, login_url='/login/')
def stu_active(request):
    code = 200
    try:
        username = request.user
        acts = models.Club_Activities.objects.filter(stu_obj__user_obj__name=username).all()
        datas = []
        for act in acts:
            enrolltime = '%s - %s' % (act.enroll_starttime, act.enroll_endtime)
            acttime = '%s - %s' % (act.act_starttime, act.act_endtime)
            number = '%s / %s' % (act.now_number, act.max_number)
            now_time = datetime.datetime.now()
            if now_time < act.enroll_endtime and now_time > act.enroll_starttime:
                status = '活动报名中'
            elif now_time < act.act_endtime and now_time > act.act_starttime:
                status = '活动进行中'
            else:
                status = '活动已结束'
            data = {'id': act.id,
                    'title': act.title,
                    'enrolltime': enrolltime,
                    'acttime': acttime,
                    'number': number,
                    'place': act.place,
                    'club': act.pl_obj.club,
                    'status': status}
            datas.append(data)
    except Exception as e:
        print(e)
        code = 400
    finally:
        return JsonResponse({
            "status": code,
            "message": "",
            "count": len(datas),
            "data": datas
        }, safe=False)


# 申请的活动
@login_required(redirect_field_name=REDIRECT_FIELD_NAME, login_url='/login/')
def reg_active1(request):
    code = 200
    try:
        username = request.user
        acts = models.Club_Activities.objects.filter(pl_obj__user_obj__name=username).all()
        datas = []
        for act in acts:
            if act.state == 0:
                status = '审核中'
            elif act.state == 1:
                status = '审核通过'
            else:
                status = '审核失败,原因:%s' % act.false
            data = {'id': act.id,
                    'title': act.title,
                    'desc': act.desc,
                    'status': status}
            datas.append(data)
    except Exception as e:
        print(e)
        code = 400
    finally:
        return JsonResponse({
            "status": code,
            "message": "",
            "count": len(datas),
            "data": datas
        }, safe=False)


# 报名结束的活动
@login_required(redirect_field_name=REDIRECT_FIELD_NAME, login_url='/login/')
def reg_active2(request):
    code = 200
    try:
        username = request.user
        now_time = datetime.datetime.now()
        acts = models.Club_Activities.objects.filter(pl_obj__user_obj__name=username, state=1).all()
        datas = []
        for act in acts:
            if now_time >= act.enroll_endtime and now_time <= act.enroll_starttime:
                status = '活动报名结束'
            elif now_time < act.act_endtime and now_time > act.act_starttime:
                status = '活动进行中'
            else:
                status = '活动已结束'
            data = {'id': act.id,
                    'title': act.title,
                    'desc': act.desc,
                    'status': status}
            datas.append(data)
    except Exception as e:
        print(e)
        code = 400
    finally:
        return JsonResponse({
            "status": code,
            "message": "",
            "count": len(datas),
            "data": datas
        }, safe=False)


# 申请
@login_required(redirect_field_name=REDIRECT_FIELD_NAME, login_url='/login/')
def apply(request):
    response = MyResponse()
    if request.method == 'POST':
        title = request.POST.get('title')
        desc = request.POST.get('desc')
        enroll_starttime = request.POST.get('enroll_starttime')
        enroll_endtime = request.POST.get('enroll_endtime')
        act_starttime = request.POST.get('act_starttime')
        act_endtime = request.POST.get('act_endtime')
        number = request.POST.get('number')
        place = request.POST.get('place')
        try:
            user = models.Student.objects.filter(user_obj__name=request.user).first()
            models.Club_Activities.objects.create(title=title,
                                                  desc=desc,
                                                  enroll_starttime=enroll_starttime,
                                                  enroll_endtime=enroll_endtime,
                                                  act_starttime=act_starttime,
                                                  act_endtime=act_endtime,
                                                  now_number=0,
                                                  max_number=number,
                                                  place=place,
                                                  pl_obj=user
                                                  )
            response.msg = '申请成功'
        except Exception as e:
            print(e)
            response.status = 200
            response.msg = '申请失败'
    return JsonResponse(response.get_dic)


# 导出
@login_required(redirect_field_name=REDIRECT_FIELD_NAME, login_url='/login/')
def export_excel(request):
    res = MyResponse()
    if request.method == 'POST':
        try:
            # 设置HTTPResponse的类型
            response = HttpResponse(content_type='application/vnd.ms-excel')
            response['Content-Disposition'] = 'attachment;filename=order.xls'
            # 创建一个文件对象
            wb = xlwt.Workbook(encoding='utf8')
            # 创建一个sheet对象
            sheet = wb.add_sheet('order-sheet')

            # 设置文件头的样式,这个不是必须的可以根据自己的需求进行更改
            style_heading = xlwt.easyxf("""
                    font:
                        name Arial,
                        colour_index white,
                        bold on,
                        height 0xA0;
                    align:
                        wrap off,
                        vert center,
                        horiz center;
                    pattern:
                        pattern solid,
                        fore-colour 0x19;
                    borders:
                        left THIN,
                        right THIN,
                        top THIN,
                        bottom THIN;
                    """)

            # 写入文件标题
            sheet.write(0, 0, '姓名', style_heading)
            sheet.write(0, 1, '性别', style_heading)
            sheet.write(0, 2, '联系方式', style_heading)
            sheet.write(0, 3, '所属专业', style_heading)
            sheet.write(0, 4, '所属班级', style_heading)
            sheet.write(0, 5, '所属社团', style_heading)

            # 写入数据
            data_row = 1
            # UserTable.objects.all()这个是查询条件,可以根据自己的实际需求做调整.
            club_id = request.POST.get('id')
            club = models.Club_Activities.objects.filter(id=club_id).first()
            students = club.stu_obj.all()
            for student in students:
                # 格式化datetime
                if student.user_obj.sex == 0:
                    sex = '女'
                else:
                    sex = '男'
                sheet.write(data_row, 0, student.user_obj.name)
                sheet.write(data_row, 1, sex)
                sheet.write(data_row, 2, student.user_obj.phone)
                sheet.write(data_row, 3, student.major)
                sheet.write(data_row, 4, student.stu_class)
                sheet.write(data_row, 5, student.club)
                data_row = data_row + 1
            file_name = '%s-%s.xls'%(club.pl_obj.user_obj.name,club.title)
            file_path = "C:\\Users\\Administrator\\Desktop\\%s"%file_name
            exist_file = os.path.exists(file_path)
            if exist_file:
                os.remove(file_path)
            wb.save(file_path)
            # 写出到IO
            output = BytesIO()
            wb.save(output)
            # 重新定位到开始
            output.seek(0)
            response.write(output.getvalue())
            res.msg='导出成功'
        except Exception as e:
            print(e)
            res.status = 200
            res.msg = '导出失败'
        return JsonResponse(res.get_dic)

# 审核中的活动
@login_required(redirect_field_name=REDIRECT_FIELD_NAME, login_url='/login/')
def exa_active1(request):
    code = 200
    try:
        acts = models.Club_Activities.objects.filter(state=0).all()
        datas = []
        for act in acts:
            enrolltime = '%s - %s' % (act.enroll_starttime, act.enroll_endtime)
            acttime = '%s - %s' % (act.act_starttime, act.act_endtime)
            status = '审核中'
            data = {'id': act.id,
                    'title': act.title,
                    'enrolltime': enrolltime,
                    'acttime': acttime,
                    'number': act.max_number,
                    'place': act.place,
                    'club': act.pl_obj.club,
                    'pl_obj': act.pl_obj.user_obj.name,
                    'status': status}
            datas.append(data)
    except Exception as e:
        print(e)
        code = 400
    finally:
        return JsonResponse({
            "status": code,
            "message": "",
            "count": len(datas),
            "data": datas
        }, safe=False)


# 审核后的活动
@login_required(redirect_field_name=REDIRECT_FIELD_NAME, login_url='/login/')
def exa_active2(request):
    code = 200
    try:
        acts = models.Club_Activities.objects.filter(Q(state=1) | Q(state=2)).all()
        datas = []
        for act in acts:
            enrolltime = '%s - %s' % (act.enroll_starttime, act.enroll_endtime)
            acttime = '%s - %s' % (act.act_starttime, act.act_endtime)
            if act.state == 1:
                status = '审核通过'
            else:
                status = '审核失败,原因%s' % act.false
            data = {'id': act.id,
                    'title': act.title,
                    'enrolltime': enrolltime,
                    'acttime': acttime,
                    'number': act.max_number,
                    'place': act.place,
                    'club': act.pl_obj.club,
                    'pl_obj': act.pl_obj.user_obj.name,
                    'status': status}
            datas.append(data)
    except Exception as e:
        print(e)
        code = 400
    finally:
        return JsonResponse({
            "status": code,
            "message": "",
            "count": len(datas),
            "data": datas
        }, safe=False)


# 审核成功
@login_required(redirect_field_name=REDIRECT_FIELD_NAME, login_url='/login/')
def success(request):
    response = MyResponse()
    if request.method == 'POST':
        id = request.POST.get('id')
        print(id)
        try:
            models.Club_Activities.objects.filter(pk=id).update(state=1)
            response.msg = '审核成功'
        except Exception as e:
            print(e)
            response.status = 200
            response.msg = '数据异常'
    return JsonResponse(response.get_dic)


# 审核失败
@login_required(redirect_field_name=REDIRECT_FIELD_NAME, login_url='/login/')
def fail(request):
    response = MyResponse()
    if request.method == 'POST':
        id = request.POST.get('id')
        fail = request.POST.get('fail')
        print(id, fail)
        try:
            models.Club_Activities.objects.filter(pk=id).update(false=fail, state=2)
            response.msg = '审核成功'
        except Exception as e:
            print(e)
            response.status = 200
            response.msg = '数据异常'
    return JsonResponse(response.get_dic)


# 报名
@login_required(redirect_field_name=REDIRECT_FIELD_NAME, login_url='/login/')
def sign_up(request):
    response = MyResponse()
    if request.method == 'POST':
        try:
            username = request.user
            club_id = request.POST.get('id')
            user = models.Student.objects.filter(user_obj__name=username).first()
            with transaction.atomic():
                club = models.Club_Activities.objects.select_for_update().get(id=club_id)
                club.now_number = F('now_number')+1
                club.save()
                club.stu_obj.add(user)
            response.msg = '报名成功'
        except Exception as e:
            print(e)
            response.status = 200
            response.msg = '报名失败'
    return JsonResponse(response.get_dic)
